package com.hefan.common.oss;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.model.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSErrorCode;
import com.aliyun.oss.OSSException;
import com.cat.tiger.util.GlobalConstants;
import com.hefan.common.ons.ONSConstants;

/**
 * Created by zhangweiwei on 14-9-15.
 */
@Component("ossImageService")
public class OssImageService {

    // 演示，创建Bucket的时候，endpoint不能带上.
    // 图片上传和简单的图片访问也可以用这个。
    public static String endpoint = "http://oss-cn-beijing.aliyuncs.com";

    // 图片处理，需要用单独的地址。访问、裁剪、缩放、效果、水印、格式转换等服务。
    // public static String endpointImg = "http://img-cn-hangzhou.aliyuncs.com";

    // 单例，只需要建立一次链接
    private static OSSClient client = null;

    //配置参数
    static ClientConfiguration config() {
        ClientConfiguration conf = new ClientConfiguration();
        conf.setMaxConnections(200);
        conf.setConnectionTimeout(20000);
        conf.setMaxErrorRetry(0);
        conf.setSocketTimeout(20000);
        return conf;
    }

    //客户端
    public static OSSClient client() {
        if (client == null) {
            ClientConfiguration conf = config();
            client = new OSSClient(endpoint, ONSConstants.AccessKey, ONSConstants.SecretKey, conf);
        }
        return client;
    }

    //上传一个文件，InputStream
    public static void uploadFile(String bucketName, InputStream is, String key) {
        OSSClient client = client();
        PutObjectRequest putObjectRequest = new PutObjectRequest(
                bucketName, key, is);
        client.putObject(putObjectRequest);
    }

    //上传一个文件，File
    public static void uploadFile(String bucketName, File file, String key) {
        OSSClient client = client();
        PutObjectRequest putObjectRequest = new PutObjectRequest(
                bucketName, key, file);
        client.putObject(putObjectRequest);
    }

    //下载一个文件到本地
    public static OSSObject downloadFile(String bucketName, String key) {
        OSSClient client = client();
        GetObjectRequest getObjectRequest = new GetObjectRequest(
                bucketName, key);
        OSSObject object = client.getObject(getObjectRequest);
        return object;
    }

    //创建目录，不能以斜杠“/”开头
    public static void makeDir(String bucketName, String keySuffixWithSlash) {
        OSSClient client = client();
        /*
         * Create an empty folder without request body, note that the key must
         * be suffixed with a slash
         */
        if (StringUtils.isEmpty(keySuffixWithSlash)) {
            return;
        }
        if (!keySuffixWithSlash.endsWith("/")) {
            keySuffixWithSlash += "/";
        }
        client.putObject(bucketName, keySuffixWithSlash,
                new ByteArrayInputStream(new byte[0]));
    }

    public String updataFile(String bucket, InputStream file, long filelength, String fileName) throws Exception {
        OSSClient client = client();
        String keyStr = "";
        PutObjectResult result = null;
        try {
            // 创建上传Object的Metadata
            ObjectMetadata meta = new ObjectMetadata();
            // 必须设置ContentLength
            // 若不设置将以Chunked方式上传
            meta.setContentLength(filelength);
            // 上传Object.
            // bucket 命名空间
            // key object的名字
            // content object数据
            // meta 用户对该object的描述，由一系列name-value对组成
            result = client.putObject(bucket, fileName, file, meta);

        } catch (Exception e) {
            throw e;
        }
        return result.getETag();
    }

    public String uploadFileToOSS(String bucket, InputStream file, long filelength, String fileName) throws FileNotFoundException {
        // 创建上传Object的Metadata
        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentLength(filelength);
        OSSClient client = client();
        String resStr = "";
        //上传
        try {
            PutObjectResult result = client.putObject(bucket, fileName, file, meta);
            resStr = result.getETag();

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return resStr;

    }

    /**
     * 追加上传
     *
     * @param bucketName
     * @param filePath
     * @param content
     * @throws IOException
     * @throws
     * @Title: appendObjectToOSS
     * @Description: TODO(这里用一句话描述这个方法的作用)
     * @return: void
     * @author: LiTeng
     * @date: 2016年10月13日 下午5:50:02
     */
    public void appendObjectToOSS(String bucketName, String filePath, String content) throws IOException {
        OSSClient oSSClient = client();
        try {
            long nextPosition = 0L;
            AppendObjectRequest appendObjectRequest = new AppendObjectRequest(bucketName, filePath,
                    new ByteArrayInputStream(content.getBytes()));
            //判断文件是否存在-存在取追加未知/不存在默认追加未知为0
            if (oSSClient.doesObjectExist(bucketName, filePath)) {
                SimplifiedObjectMeta objectMeta = oSSClient.getSimplifiedObjectMeta(bucketName, filePath);
                nextPosition = objectMeta.getSize();
            }
            try {
                oSSClient.appendObject(appendObjectRequest.withPosition(nextPosition));
            } catch (OSSException ose) {
                //文件不存在/位置不对再传一次，只续传一次。(高并发，暂不用递归)
                if (ose.getErrorCode().equals(OSSErrorCode.NO_SUCH_KEY)
                        || ose.getErrorCode().equals(OSSErrorCode.POSITION_NOT_EQUAL_TO_LENGTH)) {
                    SimplifiedObjectMeta objectMeta = oSSClient.getSimplifiedObjectMeta(bucketName, filePath);
                    nextPosition = objectMeta.getSize();
                    oSSClient.appendObject(appendObjectRequest.withPosition(nextPosition));
                } else {
                    throw ose;
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                throw e;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        /*
         * Constructs a client instance with your account for accessing OSS
         */
        OssImageService is = new OssImageService();
//    	is.appendObjectToOSS("hefanimage", "hahaha/aptest123.txt", String.valueOf(new Date().getTime()));
//    	InputStream inputStream = new FileInputStream("E:/sensitive/sensitiveWords.txt");
//    	 try {
//             OSSClient oSSClient = null;
//             oSSClient = new OSSClient(OSS_ENDPOINT,ONSConstants.AccessKey, ONSConstants.SecretKey);
//             PutObjectResult result = oSSClient.putObject("hefanimage", "hahaha/sensitiveWords.txt", inputStream);
//             System.out.println(result.toString());
//         } catch (Exception ex) {
//             ex.printStackTrace();
//         }
        List<String> list = new ArrayList<String>();
        list.add("123");
        list.add("456");
        StringBuffer contentBuffer = new StringBuffer();
        for (String content : list) {
            if (StringUtils.isBlank(content)) {
                continue;
            }
            contentBuffer.append(content);
            contentBuffer.append("\n"); // don't forget the return character
        }
        try {
            ByteArrayInputStream buf = new ByteArrayInputStream(contentBuffer.toString().getBytes("utf-8"));
            is.updataFile(GlobalConstants.PIC_OSS_BUCKET, buf, buf.available(), "test_hefantv/SensitiveWord.txt");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
